package ua.kharkov.knure.pereverziev.diploma.web.command.ajax;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.entity.Route;
import ua.kharkov.knure.pereverziev.diploma.web.command.Command;

public class GetPrice implements Command {

	private static final long serialVersionUID = -1004195229302087661L;

	public static final int FLIGHT_DIRECT = 1;
	public static final int FLIGHT_RETURN = 2;

	private static final Logger log = Logger.getLogger(GetPrice.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {

		final String route = request.getParameter("route");
		log.debug("Request parameter: route --> " + route);

		final String direction = request.getParameter("direction");
		log.debug("Request parameter: direction --> " + direction);

		float price = 0f;
		final StringBuilder stringBuilder = new StringBuilder();
		final StringBuilder services = new StringBuilder();

		@SuppressWarnings("unchecked")
		final List<Route> directFlights = (List<Route>) request.getSession()
				.getAttribute("directFlights");
		@SuppressWarnings("unchecked")
		final List<Route> returnFlights = (List<Route>) request.getSession()
				.getAttribute("returnFlights");

		stringBuilder.append("Flight: ");
		if (Integer.parseInt(direction) == FLIGHT_DIRECT) {
			price += directFlights.get(Integer.parseInt(route)).getPriceFloat();
			stringBuilder.append(route != null ? directFlights.get(
					Integer.parseInt(route)).getPrice() : "0");
		} else {
			price += returnFlights.get(Integer.parseInt(route)).getPriceFloat();
			stringBuilder.append(route != null ? returnFlights.get(
					Integer.parseInt(route)).getPrice() : "0");
		}

		stringBuilder.append("$ ");

		@SuppressWarnings("unchecked")
		final Map<String, String[]> params = request.getParameterMap();

		for (final String key : params.keySet()) {
			final String service = (params.get(key))[0];
			log.debug("-----------> " + key + "~" + service);
			if (key.contains("service")) {
				price += Float.parseFloat(service.split("_")[1]);
				services.append(service.split("_")[1] + "$+");
			}
		}

		String serv = "";
		if (services.length() != 0)
			serv = "+ Services: "
					+ services.toString().substring(0, services.length() - 1);

		return stringBuilder.toString() + serv + " = " + price + "$";
	}
}
